package future;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @author Jim
 * @date 8:36 下午 2022/4/9
 * @description 测试
 * @email:huwmz04153277@126.com
 */
public class Complete {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future =
                CompletableFuture.supplyAsync(new Supplier<Integer>() {
                    @Override
                    public Integer get() {
                        System.out.println(Thread.currentThread().getName() + "\t completableFuture");
                        return 1024;
                    }
                }).thenApply(new Function<Integer, Integer>() {
                    @Override
                    public Integer apply(Integer o) {
                        System.out.println("thenApply方法，上次返回结果：" + o);
                        return o * 2;
                    }
                }).whenComplete(new BiConsumer<Integer, Throwable>() {
                    @Override
                    public void accept(Integer o, Throwable throwable) {
                        System.out.println("o=" + o);
                        System.out.println("throwable=" + throwable);
                    }
                }).exceptionally(new Function<Throwable, Integer>() {
                    @Override
                    public Integer apply(Throwable throwable) {
                        System.out.println("throwable=" + throwable);
                        return 666;
                    }
                });
        System.out.println(future.get());

        List<CompletableFuture> futures = Arrays.asList(
                CompletableFuture.completedFuture("hello"),
                CompletableFuture.completedFuture(" world!"),
                CompletableFuture.completedFuture(" hello"),
                CompletableFuture.completedFuture("java!"));
        final CompletableFuture<Object> allCompleted =
                CompletableFuture.anyOf(futures.toArray(new CompletableFuture[]{}));
        allCompleted.thenRun(() ->{
            futures.stream().forEach(future1 ->{
                try {
                    System.out.println("get future at:" + System.currentTimeMillis() + ", result:" + future1.get());
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            });
        });
    }
}
